package com.itheima.service.impl;

import com.itheima.dao.StudentDao;
import com.itheima.dao.impl.StudentDaoImpl;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;

import java.util.ArrayList;

public class StudentServiceImpl implements StudentService {
    private StudentDao studentDao = new StudentDaoImpl();
    private Student student;
    private ArrayList<Student> stus = studentDao.findAllStudents();

    //注册
    @Override
    public boolean addStudent(Student stu) {
        return studentDao.addStudent(stu);
    }

    //遍历查看
    @Override
    public void findAllStudents() {
        /*for (int i = 0; i < stus.size(); i++) {
            System.out.println(stus.get(i).toString());
        }*/
        for (Student stus1 : stus) {
            System.out.println(stus1.toString());
        }

    }

    //登录
    @Override
    public boolean login(Student stu) {
        for (int i = 0; i < stus.size(); i++) {
            if (stus.get(i).getId().equals(stu.getId()) && stus.get(i).getPassword().equals(stu.getPassword())){
                //将其详细信息，封装返回
                student = new Student(stus.get(i).getName(),stus.get(i).getAge(),stus.get(i).getSubject());
                return true;
            }
        }
        return false;
    }

    //登录成功，返回详细信息
    @Override
    public Student print() {
        return student;
    }

    //判断id是否存在
    @Override
    public boolean judge(String id) {
        return studentDao.judge(id);
    }

    //修改
    @Override
    public boolean updateStudent(Student upstu) {
        int index = getIndex(upstu);
        if (index!=-1){
            stus.set(index,upstu);
            return true;
        }
        return false;
    }

    //删除
    @Override
    public boolean deleteStudent(String delid) {
        int index = getIndex(delid);
        if (index!=-1){
            stus.remove(index);
            return true;
        }
        return false;
    }

    //获取传进来的学生对象的位置
    private int getIndex(Student stu) {
        for (int i = 0; i < stus.size(); i++) {
            if (stus.get(i).getId().equals(stu.getId())){
                return i;
            }
        }
        return -1;
    }
    //重载
    private int getIndex(String id) {
        for (int i = 0; i < stus.size(); i++) {
            if (stus.get(i).getId().equals(id)){
                return i;
            }
        }
        return -1;
    }

}
